package com.sl.mes.app.service.puboid;


import com.sl.mes.app.controller.ApiRequestTools;
import com.sl.mes.db.itf.puboid.IPubOid;
import com.sl.mes.db.vo.PubOid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Component
public class OidGeneratorBS {

    private static final int OID_AMOUNT = 1000;

    @Autowired
    private IPubOid iPubOid;

    /**
     * 新增
     *
     * @param pk_corp
     * @param oid
     * @throws Exception
     */
    private void insertOidBase(String pk_corp, String oid) {
        //"insert into PUB_OID (pk_corp, idnumber) values(?,?)"
        PubOid pubOid = new PubOid();
        pubOid.setGroup(pk_corp);
        pubOid.setPubOid(oid);
        iPubOid.insertPubOid(pubOid);



    }

    private String selectForUpdateOidBase(String pk_corp) {

        String currentId = null;
        String firstId = "10000000000000";

        //TODO:先从数据库里查询id
        iPubOid.findPubOidById(pk_corp);


        if (1 == 1) {//
            currentId = "从数据库里查询id";
            if (currentId.compareTo("10000000000000") < 0) {
                currentId = firstId;
            }

            //用数据库里查询出来的id，查找一个id
            currentId = nextOidCode(currentId);

            //再更新Id
            //("update PUB_OID set idnumber=? where pk_corp=?");

            PubOid pubOid = new PubOid();
            pubOid.setGroup(pk_corp);
            pubOid.setPubOid(currentId);
            iPubOid.updataPubOid(pubOid);



        } else {
            //新增
            insertOidBase(pk_corp, nextOidCode(firstId));
            currentId = firstId;
        }

        return currentId;
    }


    private String nextOidCode(String currentId) {
        OidBaseAlgorithm oidBaseAlgrithm = OidBaseAlgorithm.getInstance(currentId);
        String nextOidBaseCode = null;

        for (int j = 0; j < 1000; j++) {
            nextOidBaseCode = oidBaseAlgrithm.nextOidBase();
        }
        return nextOidBaseCode;
    }

    public String createOidBase_RequiresNew(String pk_corp) {
        String oid = createOidBase(pk_corp);
        return oid;

    }

    private String createOidBase(String pk_corp) {
        return selectForUpdateOidBase(pk_corp);
    }
}


